package com.geeklan.smart.data.remote.rtc;

import android.content.Context;
import android.text.TextUtils;
import android.view.SurfaceView;
import android.widget.FrameLayout;

import com.geeklan.base.utils.MLog;
import com.geeklan.smart.MLMApplication;

import java.util.LinkedHashMap;
import java.util.Map;

import io.agora.mediaplayer.IMediaPlayer;
import io.agora.mediaplayer.IMediaPlayerObserver;
import io.agora.mediaplayer.data.CacheStatistics;
import io.agora.mediaplayer.data.MediaPlayerSource;
import io.agora.mediaplayer.data.PlayerPlaybackStats;
import io.agora.mediaplayer.data.PlayerUpdatedInfo;
import io.agora.mediaplayer.data.SrcInfo;
import io.agora.rtc2.ChannelMediaOptions;
import io.agora.rtc2.Constants;
import io.agora.rtc2.RtcEngine;
import io.agora.rtc2.RtcEngineConfig;
import io.agora.rtc2.proxy.LocalAccessPointConfiguration;
import io.agora.rtc2.video.VideoCanvas;

public class RtcEngineLocalManager implements IMediaPlayerObserver {
    private static final String TAG = "RtcEngineManager";
    private boolean joined = false;
    private long playerDuration = 0;
    private RtcEngine engine;
    private IMediaPlayer mediaPlayer;

    public IMediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    private ChannelMediaOptions options = new ChannelMediaOptions();
    private final Map<String, String> videoInfoMap = new LinkedHashMap<>();


    public RtcEngineLocalManager(Context context,FrameLayout fl_local){
        try {
            RtcEngineConfig config = new RtcEngineConfig();
            /*
             * The context of Android Activity
             */
            config.mContext = context.getApplicationContext();
            /*
             * The App ID issued to you by Agora. See <a href="https://docs.agora.io/en/Agora%20Platform/token#get-an-app-id"> How to get the App ID</a>
             */
            config.mAppId = com.geeklan.smart.common.Constants.DEVICE_SSID;
            /* Sets the channel profile of the Agora RtcEngine.
             CHANNEL_PROFILE_COMMUNICATION(0): (Default) The Communication profile.
             Use this profile in one-on-one calls or group calls, where all users can talk freely.
             CHANNEL_PROFILE_LIVE_BROADCASTING(1): The Live-Broadcast profile. Users in a live-broadcast
             channel have a role as either broadcaster or audience. A broadcaster can both send and receive streams;
             an audience can only receive streams.*/
            config.mChannelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING;
            /*
             * IRtcEngineEventHandler is an abstract class providing default implementation.
             * The SDK uses this class to report to the app on SDK runtime events.
             */
//            config.mEventHandler = iRtcEngineEventHandler;
            config.mAudioScenario = Constants.AudioScenario.getValue(Constants.AudioScenario.DEFAULT);
            config.mAreaCode = MLMApplication.getApplication().getGlobalSettings().getAreaCode();
            engine = RtcEngine.create(config);
            /*
             * This parameter is for reporting the usages of APIExample to agora background.
             * Generally, it is not necessary for you to set this parameter.
             */
            engine.setParameters("{"
                    + "\"rtc.report_app_scenario\":"
                    + "{"
                    + "\"appScenario\":" + 100 + ","
                    + "\"serviceType\":" + 11 + ","
                    + "\"appVersion\":\"" + RtcEngine.getSdkVersion() + "\""
                    + "}"
                    + "}");
            /* setting the local access point if the private cloud ip was set, otherwise the config will be invalid.*/
            LocalAccessPointConfiguration localAccessPointConfiguration = MLMApplication.getApplication().getGlobalSettings().getPrivateCloudConfig();
            if (localAccessPointConfiguration != null) {
                // This api can only be used in the private media server scenario, otherwise some problems may occur.
                engine.setLocalAccessPoint(localAccessPointConfiguration);
            }
            mediaPlayer = engine.createMediaPlayer();
            mediaPlayer.registerPlayerObserver(this);


            SurfaceView surfaceView = new SurfaceView(context);
            surfaceView.setZOrderMediaOverlay(false);
            if (fl_local.getChildCount() > 0) {
                fl_local.removeAllViews();
            }
            fl_local.addView(surfaceView);

            // Setup local video to render your local media player view
            VideoCanvas videoCanvas = new VideoCanvas(surfaceView, Constants.RENDER_MODE_HIDDEN, 0);
            videoCanvas.sourceType = Constants.VIDEO_SOURCE_MEDIA_PLAYER;
            videoCanvas.mediaPlayerId = mediaPlayer.getMediaPlayerId();
            engine.setupLocalVideo(videoCanvas);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void open(String url){
        if (!TextUtils.isEmpty(url)) {
            MediaPlayerSource source = new MediaPlayerSource();
            source.setUrl(url);
            source.setEnableMultiAudioTrack(true);
            mediaPlayer.openWithMediaSource(source);
        }
    }

    public void play(){
        mediaPlayer.play();
        playerDuration = mediaPlayer.getDuration();
    }

    public void onDestroy(){
        mediaPlayer.destroy();
    }

    @Override
    public void onPlayerStateChanged(io.agora.mediaplayer.Constants.MediaPlayerState state, io.agora.mediaplayer.Constants.MediaPlayerReason reason) {
        if(state == io.agora.mediaplayer.Constants.MediaPlayerState.PLAYER_STATE_OPEN_COMPLETED){
            play();
        }
    }

    @Override
    public void onPositionChanged(long positionMs, long timestampMs) {
        MLog.e(TAG,"playerDuration = " +playerDuration + "\npositionMs = " + positionMs + "\ntimestampMs = " + timestampMs);
        if (playerDuration > 0) {
            int progress = (int) ((positionMs * 1.0 / playerDuration) * 100);
            if(rtcEngineEventListener != null) {
                rtcEngineEventListener.onPositionChanged(progress);
            }
        }
    }

    @Override
    public void onPlayerEvent(io.agora.mediaplayer.Constants.MediaPlayerEvent eventCode, long elapsedTime, String message) {

    }

    @Override
    public void onMetaData(io.agora.mediaplayer.Constants.MediaPlayerMetadataType type, byte[] data) {

    }

    @Override
    public void onPlayBufferUpdated(long playCachedBuffer) {

    }

    @Override
    public void onPreloadEvent(String src, io.agora.mediaplayer.Constants.MediaPlayerPreloadEvent event) {

    }

    @Override
    public void onAgoraCDNTokenWillExpire() {

    }

    @Override
    public void onPlayerSrcInfoChanged(SrcInfo from, SrcInfo to) {

    }

    @Override
    public void onPlayerInfoUpdated(PlayerUpdatedInfo info) {

    }

    @Override
    public void onPlayerCacheStats(CacheStatistics stats) {

    }

    @Override
    public void onPlayerPlaybackStats(PlayerPlaybackStats stats) {

    }

    @Override
    public void onAudioVolumeIndication(int volume) {

    }

    private RtcEngineEventListener rtcEngineEventListener;

    public void setRtcEngineEventListener(RtcEngineEventListener rtcEngineEventListener) {
        this.rtcEngineEventListener = rtcEngineEventListener;
    }

    public interface RtcEngineEventListener{
        void onPositionChanged(int progress);
    }
}
